import React, { useEffect, useState } from "react";
import {
  Button,
  Card,
  Form,
  Input,
  Popconfirm,
  Space,
  Table,
  message,
} from "antd";
import {
  SearchOutlined,
  DeleteOutlined,
  EditOutlined,
} from "@ant-design/icons";
import { ColumnsType } from "antd/lib/table";
import { FormFields, HospitalSetItem } from "@/api/hospital/hospitalSet/types";
import {
  reqBatchRemoveHospitalSet,
  reqGetHospitalSet,
  reqRemoveHospital,
} from "@/api/hospital/hospitalSet";
import { Link, useNavigate } from "react-router-dom";

export default function HospitalSet() {
  //状态
  let [hospital, setHospital] = useState<HospitalSetItem[]>([]);
  //定义数据总数的状态
  let [total, setTotal] = useState(0);
  //定义页码数的状态
  let [page, setPage] = useState(1);
  //定义每页显示数量的状态
  let [pageSize, setPageSize] = useState(5);
  //定义是否加载中的状态
  let [isLoading, setIsLoading] = useState(false);
  //定义表单值的状态
  let [formValues, setFormValues] = useState<FormFields>({
    hosname: "",
    hoscode: "",
  });
  //获取 form 对象
  let [form] = Form.useForm();
  //定义选中医院的 id 的状态
  let [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  //定义一个用于更新的状态
  let [fresh, setFresh] = useState({});
  //获得 navigate 函数
  let navigate = useNavigate();

  //表单提交的回调
  let onFinish = (values: FormFields) => {
    //获取表单的值
    //更新状态
    setFormValues(values);
  };

  //失败的回调
  let onFinishFailed = () => {};

  //删除医院设置的回调
  let remove = (id: React.Key) => {
    //获取 id
    return async () => {
      //发送请求, 删除医院
      await reqRemoveHospital(id);
      //成功的提醒
      message.success("删除成功");
      //更新组件 {} 
      setFresh({});
    };
  };

  //批量删除的回调
  let batchRemove = async () => {
    //调用函数 发送请求
    await reqBatchRemoveHospitalSet(selectedKeys as string[]);
    //成功的提醒
    message.success('批量删除成功');
    //刷新组件
    setFresh({});
  }

  //定义表格结构
  let columns: ColumnsType<HospitalSetItem> = [
    {
      title: "序号",
      render: (_, record, index) => {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "API基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机号",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      width: 150,
      fixed: "right",
      render: (_, record) => {
        return (
          <Space>
            <Link to={`/syt/hospital/hospitalSet/edit/${record.id}`}>
              <Button type="primary" icon={<EditOutlined />}></Button>
            </Link>
            <Popconfirm
              title="确认删除么?"
              onConfirm={remove(record.id)}
              okText="是"
              cancelText="否"
            >
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
              ></Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  //定义 useEffect 回调
  useEffect(() => {
    //声明一个异步函数
    let getData = async () => {
      //更新 isLoading 的值
      setIsLoading(true);
      //调用函数, 发送 AJAX 请求, 获取医院设置数据
      let result = await reqGetHospitalSet({
        page: page,
        limit: pageSize,
        hosname: formValues.hosname,
        hoscode: formValues.hoscode,
      });
      //更新状态
      setHospital(result.records);
      //更新总数的状态
      setTotal(result.total);
      //更新 isLoading 的值
      setIsLoading(false);
    };
    //调用函数
    getData();
  }, [page, pageSize, formValues, fresh]);

  //定义 reset 函数
  let reset = () => {
    //设置 form 表单元素的值
    form.setFieldsValue({ hosname: "", hoscode: "" });
    //更新状态
    setFormValues({ hosname: "", hoscode: "" });
    //更新 page  pageSize
    setPage(1);
  };

  return (
    <Card>
      {/* 1. 表单部分 */}
      <Form
        form={form}
        name="basic"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        layout="inline"
      >
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>

            <Button onClick={reset}>清空</Button>
          </Space>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 2. 按钮 */}
      <Space>
        <Button
          type="primary"
          onClick={() => navigate("/syt/hospital/hospitalSet/add")}
        >
          添加
        </Button>
        <Button onClick={batchRemove} danger type="primary" disabled={selectedKeys.length === 0}>
          批量删除
        </Button>
      </Space>
      <div className="h-20"></div>
      {/* 3. 表格部分 */}
      <Table
        rowSelection={{
          type: "checkbox",
          onChange: (
            selectedRowKeys: React.Key[],
            selectedRows: HospitalSetItem[]
          ) => {
            //更新选中 key 的状态
            setSelectedKeys(selectedRowKeys);
          },
        }}
        loading={isLoading}
        columns={columns}
        dataSource={hospital}
        bordered
        rowKey={"id"}
        scroll={{
          x: 1300,
        }}
        // 分页相关的配置
        pagination={{
          total: total,
          pageSize: pageSize,
          current: page,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15, 20],
          showQuickJumper: true,
          showTotal: (total) => {
            return `总计: ${total} 条`;
          },
          //绑定 onChange 事件
          onChange: (page: number, pageSize: number) => {
            //更新两个页码相关的状态
            setPage(page);
            setPageSize(pageSize);
          },
        }}
      />
    </Card>
  );
}
